package com.sicnu.cheer.leaugebar.managemodule.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.bean.JoinLeagueBean;
import com.sicnu.cheer.generalmodule.bean.LeagueBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.widget.NoDoubleClickListener;
import com.sicnu.cheer.leaugebar.managemodule.R;
import com.sicnu.cheer.leaugebar.managemodule.utils.DialogUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class ApplyJoinLeagueActivity extends BaseActivity implements View.OnClickListener {

    private TextView joinLeagueTV;
    private ProgressDialog progressDialog;
    private TextView chooseGradeTV;
    private TextView chooseMajorTV;
    private TextView setQQTV;
    private LeagueBean bean;
    private EditText selfIntroduceET;
    private MyUser myUser;

    @Override
    public int getContentViewId() {
        return R.layout.activity_join_league;
    }

    @Override
    protected void initView() {
        super.initView();
        findViewById(R.id.back).setOnClickListener(this);
        ((TextView) findViewById(R.id.title)).setText("填写申请表");
        joinLeagueTV = ((TextView) findViewById(R.id.join_league_tv));
        joinLeagueTV.setOnClickListener(this);
        chooseGradeTV = ((TextView) findViewById(R.id.choose_grade_tv));
        chooseGradeTV.setOnClickListener(this);
        chooseMajorTV = ((TextView) findViewById(R.id.choose_major_tv));
        chooseMajorTV.setOnClickListener(this);
        setQQTV = ((TextView) findViewById(R.id.set_qq_tv));
        setQQTV.setOnClickListener(this);
        findViewById(R.id.submit_btn).setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onClick(View v) {
                super.onClick(v);
                CheckSubmit();
            }
        });
        selfIntroduceET = ((EditText) findViewById(R.id.self_introduce_et));
        final TextView charCount = (TextView) findViewById(R.id.character_count_tv);
        selfIntroduceET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                charCount.setText(selfIntroduceET.getText().toString().length()+"/300");
            }
        });
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        myUser = MyUser.getCurrentUser(mThis,MyUser.class);
        if (!StringUtils.isEmpty(myUser.getGrade())) {//如果当前用户有年级信息
            findViewById(R.id.grade_ll).setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(myUser.getMajor())) {//如果当前用户有专业信息
            findViewById(R.id.major_ll).setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(myUser.getQq())) {//如果当前用户有QQ信息
            findViewById(R.id.qq_ll).setVisibility(View.GONE);
        }
    }
    private void CheckSubmit() {
        if (bean==null){
            UIHelper.ToastMessage(mThis,"请选择将要加入的社团");
            return;
        }
        boolean shouldUpdateUserInfo=false;
        if (StringUtils.isEmpty(myUser.getGrade())) {//如果当前用户没有年级信息
            String grade = chooseGradeTV.getText().toString();
            if (StringUtils.isEmpty(grade)) {
                UIHelper.ToastMessage(mThis, "请选择年级");
                return;
            }else {
                myUser.setGrade(grade);
                shouldUpdateUserInfo=true;
            }
        }

        if (StringUtils.isEmpty(myUser.getMajor())) {//如果当前用户没有专业信息
            String major=chooseMajorTV.getText().toString();
            if (StringUtils.isEmpty(major)){
                UIHelper.ToastMessage(mThis,"请选择专业");
                return;
            }else {
                myUser.setMajor(major);
                shouldUpdateUserInfo=true;
            }
        }

        if (StringUtils.isEmpty(myUser.getQq())) {//如果当前用户没有qq信息
            String qq=setQQTV.getText().toString();
//            if (StringUtils.isEmpty(qq))
//            {
//                UIHelper.ToastMessage(mThis,"请填写qq");
//                return;
//            }else {
                myUser.setQq(qq);
                shouldUpdateUserInfo=true;
//            }
        }

        String selfIntroduce=selfIntroduceET.getText().toString();
        if (StringUtils.isEmpty(selfIntroduce)){
            UIHelper.ToastMessage(mThis,"请填写入团理由");
            return;
        }

        progressDialog.show();
        if (shouldUpdateUserInfo) {
            //需要更新用户信息时
            myUser.update(mThis, myUser.getObjectId(), new UpdateListener() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onFailure(int i, String s) {
                }
            });
        }
        //提交申请表
        JoinLeagueBean joinLeagueBean=new JoinLeagueBean();
        joinLeagueBean.setLeagueBean(bean);
        joinLeagueBean.setMyUser(myUser);
        joinLeagueBean.setPass(0);
        joinLeagueBean.setManager(false);
        joinLeagueBean.setSelfIntroduce(selfIntroduce);
        joinLeagueBean.save(mThis, new SaveListener() {
            @Override
            public void onSuccess() {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                UIHelper.ToastMessage(mThis,"提交成功");
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                UIHelper.ToastMessage(mThis,"提交失败:"+s);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();

        progressDialog = new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.back){
            onBackPressed();
        }else if (v.getId()==R.id.join_league_tv){
            chooseLeague();
        }else if (v.getId()==R.id.choose_grade_tv){
            showChooseGradeDialog();
        }else if (v.getId()==R.id.choose_major_tv){
            showChooseMajorDialog();
        }else if (v.getId()==R.id.set_qq_tv){
            showSetQQDialog();
        }
    }

    /**
     * 弹出框设置qq号码
     */
    private void showSetQQDialog() {
        DialogUtils.showSetQQDialog(mThis, new DialogUtils.DialogCallback() {
            @Override
            public void confirmCallBack(String qq) {
                setQQTV.setText(qq);
            }

            @Override
            public void cancelCallBack() {

            }
        });
    }

    /**
     * 弹出框选择专业
     */
    private void showChooseMajorDialog() {
        DialogUtils utils=new DialogUtils();
        utils.showMajorChooseDialog(mThis, new DialogUtils.DialogCallback() {
            @Override
            public void confirmCallBack(String major) {
                chooseMajorTV.setText(major);
            }

            @Override
            public void cancelCallBack() {

            }
        });
    }

    /**
     * 弹出框选择年级
     */
    private void showChooseGradeDialog() {
        DialogUtils.showGradeChooseDialog(mThis, new DialogUtils.DialogCallback() {
            @Override
            public void confirmCallBack(String grade) {
                chooseGradeTV.setText(grade);
            }

            @Override
            public void cancelCallBack() {

            }
        });
    }

    /**
     * 选择申请的社团
     */
    private void chooseLeague() {
        progressDialog.show();
        BmobQuery<LeagueBean> query=new BmobQuery<>();
        query.addWhereNotEqualTo("objectId",mThis.getResources().getString(R.string.objId));
        query.findObjects(mThis, new FindListener<LeagueBean>() {
            @Override
            public void onSuccess(List<LeagueBean> list) {
                excludeJoinedLeague(list);
            }

            @Override
            public void onError(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"获取社团信息失败："+s);
            }
        });
    }

    private void excludeJoinedLeague(final List<LeagueBean> list) {
        BmobQuery<JoinLeagueBean> query=new BmobQuery<>();
        query.addWhereEqualTo("myUser", BmobUser.getCurrentUser(mThis));
        query.addWhereEqualTo("pass",1);
        query.include("leagueBean");
        query.findObjects(mThis, new FindListener<JoinLeagueBean>() {
            @Override
            public void onSuccess(List<JoinLeagueBean> joinedList) {
                progressDialog.dismiss();
                for (JoinLeagueBean bean:joinedList){
                    for (int i=list.size()-1;i>=0;i--){
                        if (bean.getLeagueBean().getObjectId().equals(list.get(i).getObjectId())){
                            list.remove(i);
                        }
                    }
                }
                if (list.size()>0){
                    Intent intent=new Intent(mThis,LeagueDisplayActivity.class);
                    intent.putExtra("isChange",false);
                    intent.putExtra("title","选择社团");
                    ArrayList<LeagueBean> arrayList= (ArrayList<LeagueBean>) list;
                    intent.putExtra("list",arrayList);
                    startActivityForResult(intent,0);
                }else {
                    UIHelper.ToastMessage(mThis,"没有可申请的社团");
                }
            }

            @Override
            public void onError(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"获取社团信息失败："+s);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==0&&resultCode==2){
            bean = (LeagueBean) data.getSerializableExtra("bean");
            if (bean !=null){
                joinLeagueTV.setText(bean.getName());
            }
        }
    }
}
